<template>
  <el-card style="margin: 10px 0">
    <div v-show="scene == 0">
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        :disabled="categoryStore.c3Id ? false : true"
        @click="addAttr"
        v-has="`btn.Attr.add`"
      >
        添加属性
      </el-button>
      <el-table
        border
        style="margin: 10px 0; width: 100%"
        :data="tableDataList"
      >
        <el-table-column
          type="index"
          prop="prop"
          label="序号"
          width="80px"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="attrName"
          label="属性名称"
          width="180px"
          align="center"
        ></el-table-column>

        <el-table-column label="属性信息" width="width" align="center">
          <template #="{ row }">
            <div>
              <el-tag
                v-for="attr in row.attrValueList"
                :key="attr.id"
                style="margin-right: 5px"
              >
                {{ attr.valueName }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="prop" label="操作" width="180px" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="updateTradeMark(scope.row)"
              v-has="`btn.Attr.update`"
            >
              <el-icon :size="20">
                <Edit />
              </el-icon>
            </el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="Delete"
              icon-color="#FF1900"
              :title="`确定要删除${scope.row.attrName}么?`"
              @confirm="deleteAttr(scope.row.id)"
              @cancel="cancelEvent"
              width="250px"
            >
              <template #reference>
                <el-button type="danger" size="small" v-has="`btn.Attr.remove`">
                  <el-icon :size="20">
                    <Delete />
                  </el-icon>
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="currentChange"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :background="true"
        :pager-count="5"
        layout="  prev, pager, next, jumper,->,total,"
        :total="total"
      />
    </div>
    <!-- 展示添加属性与修改属性的结构 -->
    <div v-show="scene == 1">
      <el-form ref="form" label-width="80px" :inline="true">
        <el-form-item label="属性名称">
          <el-input
            v-model="attrParams.attrName"
            placeholder="请你输入属性名称"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addAttValue"
        :disabled="attrParams.attrName == '' ? true : false"
      >
        添加属性值
      </el-button>
      <el-button size="default" @click="cancel">取消</el-button>
      <el-table border :data="attrParams.attrValueList" style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column prop="prop" label="属性值">
          <!-- row:即为当前属性值对象 -->
          <template #="{ row, $index }">
            <!-- input 元素自动获取焦点   可以添加响应式的ref="refInput"-->
            <!-- <el-input
              ref="refInput"
              v-if="row.isEdit"
              size="small"
              v-model="row.valueName"
              placeholder="请你输入属性值名称"
              @blur="toLook(row, $index)"
            ></el-input> -->
            <el-input
              :ref="(vc: any) => (inputArr[$index] = vc)"
              v-if="row.isEdit"
              size="small"
              v-model="row.valueName"
              placeholder="请你输入属性值名称"
              @blur="toLook(row, $index)"
            ></el-input>
            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="prop" label="操作" width="180px">
          <template #default="scope">
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="Delete"
              icon-color="#FF1900"
              :title="`确定要删除${scope.row.valueName}么?`"
              @confirm="attrParams.attrValueList.splice(scope.$index, 1)"
              @cancel="cancelEvent"
              width="250px"
            >
              <template #reference>
                <el-button type="danger" size="small">
                  <el-icon :size="20">
                    <Delete />
                  </el-icon>
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        size="default"
        :disabled="attrParams.attrValueList.length > 0 ? false : true"
        @click="save"
      >
        保存
      </el-button>
      <el-button size="default" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, reactive, nextTick } from 'vue'
import useCategoryStore from '@/store/modules/category.ts'
import type { Attr, AttrValue } from '@/api/product/attr/type'
import { reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr'
import { ElMessage } from 'element-plus'
let categoryStore = useCategoryStore()
const props = defineProps({
  tableData: {
    type: Array,
    default: [],
  },
  getScene: {
    type: Function,
    required: true,
  },
  getAttr: {
    type: Function,
    required: true,
  },
})
//
let pageNo = ref(1)
let limit = ref(10)
let total = ref(0)
const tableDataList = computed({
  get: () => {
    let result = props.tableData
    const start = (pageNo.value - 1) * limit.value
    const end = start + limit.value
    total.value = result.length
    return result.slice(start, end)
  },
  set: () => {},
})
//定义card组件内容切换变量 scene ==0展示属性和属性值的组件 scene ==1 展示 添加与修改属性的页面
let scene = ref<number>(0)
// let refInput = ref() //将input设置成响应式数据自动获取焦点
//准备一个数组:将来存储对应的组件实例el-input 自动获取焦点
let inputArr = ref<any>([])
//收集新增的属性的数据
let attrParams = reactive<Attr>({
  attrName: '', //新增属性名称
  attrValueList: [],
  categoryId: '', //三级分类id
  categoryLevel: '3', //分类所属级别 3级
})
//添加属性按钮回调
const addAttr = () => {
  //每一次新添加属性的时候,先清空一下数据,在收集数据
  Object.assign(attrParams, {
    attrName: '', //新增属性名称
    attrValueList: [],
    categoryId: '', //三级分类id
    categoryLevel: categoryStore.c3Id, //分类所属级别 3级
  })
  //切换为添与修改属性的结构
  scene.value = 1
  props.getScene(scene)
  //   //点击这个按钮的时候收集新增属性的三级分类ID
  //   attrParams.categoryId = categoryStore.c3Id
}
//修改当前页码事件回调
const currentChange = (value: any) => {
  pageNo.value = value
}
//修改已有属性的事件回调
const updateTradeMark = (row: Attr) => {
  //切换为添与修改属性的结构
  scene.value = 1
  props.getScene(scene)
  //将已有的属性和属性值赋值给attrParams对象即可
  //   Object.assign(attrParams,row)//浅拷贝 需改新数据影响原数据 有坑
  Object.assign(attrParams, JSON.parse(JSON.stringify(row))) //深拷贝
}

//删除某一个已有属性数据 确定事件回调
const deleteAttr = async (attrId: number) => {
  //发相应的删除已有属性的请求
  let result: any = await reqRemoveAttr(attrId)
  //删除成功
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功!',
    })
    //再次重新获取一下数据
    props.getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败!',
    })
  }
}
//取消删除
const cancelEvent = () => {}
//添加属性值按钮事件回调
const addAttValue = () => {
  //点击添加属性值按钮的时候,像数组添加一个属性值对象
  attrParams.attrValueList.push({
    valueName: '',
    isEdit: true, //控制新添加的属性值是否编辑模式还是查看模式标识
  })
  //   nextTick(() => {
  //      refInput.value.focus()
  //   })
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}
//保存添加的属性值按钮
const save = async () => {
  //发请求
  let result: any = await reqAddOrUpdateAttr(attrParams)
  if (result.code == 200) {
    scene.value = 0
    ElMessage.success(`${attrParams.id ? '修改' : '添加'}属性成功!`)
    //获取全部已有属性和属性值
    props.getAttr()
  } else {
    ElMessage.error(`${attrParams.id ? '修改' : '添加'}属性失败!`)
  }
}
//添加属性取消操作
const cancel = () => {
  scene.value = 0
  props.getScene(scene)
}
//属性值表单元素input框失去焦点的是变成查看模式
const toLook = (row: AttrValue, $index: number) => {
  //非法情况判断 属性值为空1
  if (row.valueName.trim() == '') {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值内容不能为空',
    })
    return
  }
  //非法情况判断2  属性值重复
  let repeat = attrParams.attrValueList.find((item) => {
    //item!=row 判断是否重复是要排除掉自己本身后的剩余的其他元素是否重复
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    //说明当前用户添加的属性值是重复值,删除当前用户即将要添加的重复值
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }
  //相应的属性值对象isEdit变为false,展示div
  row.isEdit = false
}
//点击div文本框变成编辑模式
const toEdit = (row: AttrValue, $index: number) => {
  //相应的属性值对象isEdit变为true,展示input
  row.isEdit = true
  //点击div自动获取焦点方法二
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}
</script>

<style lang="scss" scoped></style>
